/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-29
*/
package com.rzico.order.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Coupon;
import com.rzico.basics.entity.CouponCode;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.CouponCodeService;
import com.rzico.basics.service.CouponService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.ProductService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.order.entity.*;
import com.rzico.order.model.CartCouponVo;
import com.rzico.order.model.CartItemVo;
import com.rzico.order.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 购物车控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-29
 */
@Api(description = "购物车接口")
@RestController
@RequestMapping("/cart")
public class CartController extends BaseController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CartItemService cartItemService;

    @Autowired  @Lazy
    private OrderItemService orderItemService;

    @Autowired  @Lazy
    private GroupProductService groupProductService;

    @Autowired  @Lazy
    private CouponCodeService couponCodeService;

    @Autowired  @Lazy
    private CouponService couponService;

    @Autowired  @Lazy
    private BargainProductService bargainProductService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    /**
     * 当前我购物车
     *
     * @return
    */
    @ApiOperation("当前我购物车")
    @GetMapping("/getCart")
    public CommResult<Cart> getCart(String uuid) {

        Member member = memberService.getCurrent();
        Cart result = cartService.getCurrent(member,uuid);
        if (result==null) {
            result = cartService.create(member,uuid);
        }

        result.setItemVoList(cartItemService.getItemVoList(result.getId()));

        for (CartItemVo cartItemVo:result.getItemVoList()) {
            Product product = productService.selectByPrimaryKey(cartItemVo.getProductId());
            if (product!=null) {
                if (!product.getIsMarketable() || product.getStock()<=0) {
                    cartItemVo.setChk(false);
                }
                cartItemVo.setPrice(product.getMemberPrice(member));

                CartItem cartItem = new CartItem();
                cartItem.setId(cartItemVo.getId());
                cartItem.setChk(cartItemVo.getChk());
                cartItem.setPrice(product.getMemberPrice(member));
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }
        }

        Map<String,Object> data = new HashMap<>();
        data.put("cart",result);
        return CommResult.success(data);

    }

    /**
     * 当前我购物车数量金额
     *
     * @return
     */
    @ApiOperation("当前我购物车数量金额")
    @GetMapping("/count")
    public CommResult<Cart> count(String uuid) {

        Member member = memberService.getCurrent();
        Cart result = cartService.getCurrent(member,uuid);
        Map<String,Object> data = new HashMap<>();
        if (result==null) {
            data.put("amount",0);
            data.put("quantity",0);
        } else {
            result.setItemList(cartItemService.getItemList(result.getId()));
            data.put("amount",result.getAmount());
            data.put("quantity",result.getQuantity());
        }
        return CommResult.success(data);

    }

    /**
     * 加入购物车
     **/
    @ApiOperation("加入购物车")
    @PostMapping("/add")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "promotionId", value = "活动", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> add(String uuid,Long productId,Integer quantity,Long promotionId) {
        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));

        CartItem cartItem = cart.findItem(productId);
        Boolean isNew = false;
        if (cartItem==null) {
            cartItem = new CartItem();
            cartItem.setCartId(cart.getId());
            cartItem.setPrice(BigDecimal.ZERO);
            cartItem.setQuantity(0);
            isNew = true;
        }

        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("商品ID无效");
        }
        if (!product.getIsMarketable()) {
            return CommResult.error("商品已下架");
        }
        if (product.getStock()<quantity) {
            return CommResult.error("商品已缺货");
        }
        cartItem.setProductId(productId);
        cartItem.setPrice(product.getMemberPrice(member));
        cartItem.setQuantity(cartItem.getQuantity()+quantity);
        if (product.getMaxLimit()!=null && product.getMaxLimit()>0) {
            if (cartItem.getQuantity()>product.getMaxLimit()) {
                return CommResult.error("大于限额量");
            }
        }
        cartItem.setPromotionId(promotionId);
        cartItem.setChk(true);
        if (isNew) {
            cartItemService.insertUseGeneratedKeys(cartItem);
        } else {
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }
        return CommResult.success(cartItemService.getCartItemVo(cartItem.getId()));

    }

    /**
     * 修改数量及选中
     **/
    @ApiOperation("修改数量及选中")
    @PostMapping("/update")
    @ApiImplicitParams({
    })
    public CommResult<Cart> update(@RequestBody List<CartItem> cartItems) {
        for (CartItem cartItem:cartItems) {
            CartItem chk = new CartItem();
            if (cartItem.getChk()==null) {
                chk.setChk(true);
            } else {
                chk.setChk(cartItem.getChk());
            }
            chk.setId(cartItem.getId());
            chk.setQuantity(cartItem.getQuantity());
            cartItemService.updateByPrimaryKeySelective(chk);
        }
        return CommResult.success();

    }

    /**
     * 立即购买
     **/
    @ApiOperation("立即购买")
    @PostMapping("/buyNow")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "promotionId", value = "活动", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNow(String uuid,Long productId,Integer quantity,Long promotionId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        Boolean isNew = false;
        CartItem cartItem = cart.findItem(productId);
        if (cartItem==null) {
            cartItem = new CartItem();
            cartItem.setCartId(cart.getId());
            cartItem.setPrice(BigDecimal.ZERO);
            cartItem.setQuantity(0);
            isNew = true;

        }
        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("商品ID无效");
        }
        if (!product.getIsMarketable()) {
            return CommResult.error("商品已下架");
        }
        cartItem.setProductId(productId);
        cartItem.setChk(true);
        cartItem.setPrice(product.getMemberPrice(member));
        cartItem.setQuantity(quantity);
        cartItem.setPromotionId(promotionId);
        if (isNew) {
            cartItemService.insertUseGeneratedKeys(cartItem);
        } else {
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }
        return CommResult.success();

    }


    /**
     * 立即购买团购商品
     **/
    @ApiOperation("立即购买团购商品")
    @PostMapping("/buyNowForGroupBuy")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupBuyId", value = "订单号", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForGroupBuy(String uuid,Long groupBuyId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<GroupProduct> itemList = groupProductService.getItemList(groupBuyId);

        for (GroupProduct groupProduct:itemList) {

            Boolean isNew = false;
            CartItem cartItem = cart.findItem(groupProduct.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            Product product = productService.selectByPrimaryKey(groupProduct.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }

            cartItem.setProductId(groupProduct.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(groupProduct.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }


    /**
     * 立即购买兑换券购买
     **/
    @ApiOperation("立即购买兑换券购买")
    @PostMapping("/buyNowForCoupon")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForCoupon(@RequestBody List<CartCouponVo> cartCouponVo,String uuid) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        for (CartCouponVo couponCodeVo:cartCouponVo) {

            CouponCode couponCode = couponCodeService.selectByPrimaryKey(couponCodeVo.getId());
            Coupon coupon = couponService.selectByPrimaryKey(couponCode.getCouponId());
            Product product = productService.selectByPrimaryKey(coupon.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }


            Boolean isNew = false;
            CartItem cartItem = cart.findItem(product.getId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            cartItem.setProductId(product.getId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(coupon.getQuantity().intValue()*couponCodeVo.getQuantity());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }

    /**
     * 立即购买砍价商品
     **/
    @ApiOperation("立即购买砍价商品")
    @PostMapping("/buyNowForBargainBuy")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bargainBuyId", value = "砍价ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyNowForBarginBuy(String uuid,Long bargainBuyId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<BargainProduct> itemList = bargainProductService.getItemList(bargainBuyId);

        for (BargainProduct groupProduct:itemList) {

            Boolean isNew = false;
            CartItem cartItem = cart.findItem(groupProduct.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }

            Product product = productService.selectByPrimaryKey(groupProduct.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }

            cartItem.setProductId(groupProduct.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getPrice());
            cartItem.setQuantity(groupProduct.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }

        }
        return CommResult.success();

    }

    /**
     * 再来一单
     **/
    @ApiOperation("再来一单")
    @PostMapping("/buyForOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单号", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", dataType = "Long", paramType = "query")
    })
    public CommResult<Cart> buyForOrder(String uuid,Long orderId) {

        Member member = memberService.getCurrent();
        Cart cart = cartService.getCurrent(member,uuid);
        if (cart==null) {
            cart = cartService.create(member,uuid);
        }
        cart.setItemList(cartItemService.getItemList(cart.getId()));
        for (CartItem cartItem:cart.getItemList()) {
            cartItem.setChk(false);
            cartItemService.updateByPrimaryKeySelective(cartItem);
        }

        List<OrderItem> itemList = orderItemService.getItemList(orderId);

        for (OrderItem orderItem:itemList) {
            if (orderItem.getIsGift()==true) {
                break;
            }
            Boolean isNew = false;
            CartItem cartItem = cart.findItem(orderItem.getProductId());
            if (cartItem == null) {
                cartItem = new CartItem();
                cartItem.setCartId(cart.getId());
                cartItem.setPrice(BigDecimal.ZERO);
                cartItem.setQuantity(0);
                isNew = true;

            }
            Product product = productService.selectByPrimaryKey(orderItem.getProductId());
            if (product == null) {
                return CommResult.error("商品ID无效");
            }
            if (!product.getIsMarketable()) {
                return CommResult.error("商品已下架");
            }
            cartItem.setProductId(orderItem.getProductId());
            cartItem.setChk(true);
            cartItem.setPrice(product.getMemberPrice(member));
            cartItem.setQuantity(orderItem.getQuantity().setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue());
            cartItem.setPromotionId(null);
            if (isNew) {
                cartItemService.insertUseGeneratedKeys(cartItem);
            } else {
                cartItemService.updateByPrimaryKeySelective(cartItem);
            }
        }
        return CommResult.success();

    }

    /**
     * 批量删除购物车商品
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除购物车商品", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除购物车商品,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Cart> del(@PathVariable String ids) {

        int affectCount =  cartItemService.deleteByIds(ids.split(","));
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success();

    }

    /**
     * 测试订单回调
     *
     * @param id
     * @return
     */

    @GetMapping("/orderTest/{id}")
    public void orderTest(Long id) {
//        String code = memberService.getMaxCode("10216");
        orderService.received(5734L,false);
//        System.out.println(code);
    }


}
